<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in stats" :key="stat.title">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                <el-icon><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-title">{{ stat.title }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>资产分类分布</span>
              </div>
            </template>
            <div class="chart-container">
              <v-chart :option="pieChartOption" style="height: 300px" />
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>资产价值趋势</span>
              </div>
            </template>
            <div class="chart-container">
              <v-chart :option="lineChartOption" style="height: 300px" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最近资产列表 -->
    <div class="recent-assets">
      <el-card class="recent-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>最近添加的资产</span>
            <el-button link type="primary" size="small" @click="$router.push('/asset/list')">
              查看全部
            </el-button>
          </div>
        </template>
        
        <el-table :data="recentAssets" stripe style="width: 100%">
          <el-table-column prop="name" label="资产名称" />
          <el-table-column prop="category" label="分类" />
          <el-table-column prop="value" label="价值">
            <template #default="scope">
              ¥{{ scope.row.value.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="viewAsset(scope.row)">
                查看
              </el-button>
              <el-button link type="warning" size="small" @click="editAsset(scope.row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, markRaw, type Ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Box, Plus, Money, Tools } from '@element-plus/icons-vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { dashboardApi, assetApi, categoryApi } from '@/api'
import { AssetStatusCodeToText } from '@/utils/status'

use([
  CanvasRenderer,
  PieChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const router = useRouter()

interface StatCard { title: string; value: string | number; icon: any; color: string }
const stats = ref<StatCard[]>([]) as Ref<StatCard[]>

// 饼图配置
const pieChartOption = ref<any>({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    textStyle: {
      color: '#ffffff'
    }
  },
  series: [{ name: '资产分类', type: 'pie', radius: '50%', data: [] }]
})

// 折线图配置
const lineChartOption = ref<any>({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['资产价值'],
    textStyle: {
      color: '#ffffff'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    axisLabel: {
      color: '#ffffff'
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: '#ffffff'
    }
  },
  series: [{ name: '资产价值', type: 'line', stack: 'Total', data: [], smooth: true }]
})

// 最近资产数据
const recentAssets = ref<any[]>([])

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case '正常':
      return 'success'
    case '维护中':
      return 'warning'
    case '故障':
      return 'danger'
    case '报废':
      return 'danger'
    default:
      return 'info'
  }
}

// 查看资产
const viewAsset = (asset: any) => {
  router.push(`/asset/detail/${asset.id}`)
}

// 编辑资产
const editAsset = (asset: any) => {
  router.push(`/asset/edit/${asset.id}`)
}

// 拉取仪表盘数据
const loadDashboard = async () => {
  const dataRes: any = await dashboardApi.getData()
  stats.value = [
    { title: '总资产数量', value: dataRes.assetCount || 0, icon: markRaw(Box), color: '#409eff' },
    { title: '资产总价值', value: `¥${Number(dataRes.totalValue || 0).toLocaleString()}`, icon: markRaw(Money), color: '#67c23a' },
    { title: '本月新增', value: dataRes.newAssetsThisMonth || 0, icon: markRaw(Plus), color: '#e6a23c' },
    { title: '待维护', value: dataRes.pendingMaintenance || 0, icon: markRaw(Tools), color: '#f56c6c' }
  ]

  const catRes: any = await dashboardApi.getAssetStats()
  // 将分类名称直接作为 name，确保中文正常展示
  pieChartOption.value.series[0].data = (catRes || []).map((item: any) => ({
    name: item.name,
    value: Number(item.value || 0)
  }))

  const trendRes:any = await dashboardApi.getTrendData()
  lineChartOption.value.xAxis.data = trendRes.map((t:any)=> t.date)
  lineChartOption.value.series[0].data = trendRes.map((t:any)=> Number(t.assetCnt))

  const assetRes: any = await assetApi.getList({ current: 1, size: 3 })
  // 获取分类映射
  const categories: any[] = await categoryApi.getAll()
  const catMap = Object.fromEntries(categories.map((c:any)=>[c.id, c.name]))
  const rows = assetRes.list || assetRes.records || []
  recentAssets.value = rows.map((r:any)=>({
    ...r,
    category: catMap[r.categoryId] || '-',
    status: AssetStatusCodeToText[r.status] || '未知',
    createTime: r.createdAt || r.createTime || ''
  }))
}

onMounted(() => {
  loadDashboard()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  color: white;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--text-color);
  margin-bottom: 5px;
}

.stat-title {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  height: 300px;
}

.recent-card {
  height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard {
    padding: 15px;
  }
  
  .stats-cards .el-col {
    margin-bottom: 15px;
  }
  
  .charts-section .el-col {
    margin-bottom: 15px;
  }
}

@media (max-width: 576px) {
  .dashboard {
    padding: 10px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }
}

/* 指定中文字体，避免 canvas 渲染乱码 */
.dashboard, .chart-container {
  font-family: "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", sans-serif;
}
</style> 